﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TechTalk.SpecFlow;
using Agility.TestProject.AppDriver;
using Agility.TestProject.WebAii;

namespace Agility.Testing.Web.Features
{
    [Binding]
    public class EventDefinitions
    {
        private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

        [BeforeStep]
        public void BeforeStep()
        {
            //TODO: implement logic that has to run before each scenario step
            // For storing and retrieving scenario-specific data, 
            // the instance fields of the class or the
            //     ScenarioContext.Current
            // collection can be used.
            // For storing and retrieving feature-specific data, the 
            //     FeatureContext.Current
            // collection can be used.
            // Use the attribute overload to specify tags. If tags are specified, the event 
            // handler will be executed only if any of the tags are specified for the 
            // feature or the scenario.
            //     [BeforeStep("mytag")]
        }

        [AfterStep]
        public void AfterStep()
        {
            //TODO: implement logic that has to run after each scenario step
        }

        [BeforeScenarioBlock]
        public void BeforeScenarioBlock()
        {
            //TODO: implement logic that has to run before each scenario block (given-when-then)
        }

        [AfterScenarioBlock]
        public void AfterScenarioBlock()
        {
            //TODO: implement logic that has to run after each scenario block (given-when-then)
        }

        [BeforeScenario]
        public void BeforeScenario()
        {
            logger.Debug("Scenario: {0}", ScenarioContext.Current.ScenarioInfo.Title);
            if (FeatureContext.Current.FeatureInfo.Tags.Contains("SilverLight"))
            {
                AgilitySilverLightDriver agilitySilverlightDriver = new AgilitySilverLightDriver();
                ScenarioContext.Current.Add("AppDriver", agilitySilverlightDriver);
            }
            if (FeatureContext.Current.FeatureInfo.Tags.Contains("MSExcel"))
            {
                AgilityExcelDriver appDriver = new AgilityExcelDriver();
                ScenarioContext.Current.Add("AppDriver", appDriver);
            }
        }
        
        [AfterScenario]
        public void AfterScenario()
        {
            if (FeatureContext.Current.FeatureInfo.Tags.Contains("MSExcel"))
            {
                ((AgilityExcelDriver)ScenarioContext.Current["AppDriver"]).Cleanup();
            }
            if (FeatureContext.Current.FeatureInfo.Tags.Contains("SilverLight"))
            {
                ((AgilitySilverLightDriver)ScenarioContext.Current["AppDriver"]).Cleanup();
            }
            logger.Debug("Scenario {0} completed\r\n", ScenarioContext.Current.ScenarioInfo.Title);
        }
        
        [BeforeFeature]
        public static void BeforeFeature()
        {
            logger.Debug("--> Entering BerforeFeature");
            logger.Debug("Feature: {0}", FeatureContext.Current.FeatureInfo.Title);
            logger.Debug("<-- Leaving BerforeFeature");
        }

        [AfterFeature]
        public static void AfterFeature()
        {
            logger.Debug("--> Entering AfterFeature");
            logger.Debug("Feature {0} completed\r\n", FeatureContext.Current.FeatureInfo.Title);
            logger.Debug("<-- Leaving AfterFeature");
        }

        [BeforeTestRun]
        public static void BeforeTestRun()
        {
            logger.Debug("--> Entering BeforeTestRun");
            System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName("iisexpress");
            if(processes.Length == 0)
            {
                logger.Warn("IIS Express is not running.");
                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(@"C:\Program Files (x86)\IIS Express\iisexpress.exe");       
                startInfo.Arguments = string.Format(System.Globalization.CultureInfo.InvariantCulture, "/config:iisexpress.config");
                startInfo.CreateNoWindow = true;
                System.Diagnostics.Process process = System.Diagnostics.Process.Start(startInfo);
                logger.Debug("Started IISExpress with PID {0}", process.Id);
            }
            else
            {
                logger.Debug("Found IISExpress running with PIDs {0}", string.Join(", ", processes.Select<System.Diagnostics.Process, string>(p => p.Id.ToString())));
            }
            logger.Debug("<-- Leaving BeforeTestRun");
        }

        [AfterTestRun]
        public static void AfterTestRun()
        {
            logger.Debug("--> Entering AfterTestRun");
            System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName("iisexpress");
            foreach (System.Diagnostics.Process process in processes)
            {
                process.Close();
                logger.Debug("Stopped IISExpress with PID {0}", process.Id);   
            }
            logger.Debug("<-- Leaving AfterTestRun");
        }
    }
}
